package com.azkj.album.view.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.azkj.album.R;
import com.azkj.album.dto.LoginBean;
import com.azkj.album.dto.MessageEvent;
import com.azkj.album.dto.MessageType;
import com.azkj.album.network.ConfigStorage;
import com.azkj.album.network.networkframe.net.HttpsUtil;
import com.azkj.album.network.utils.StoreUtils;
import com.azkj.album.network.utils.ToastUtils;
import com.azkj.album.presenter.BindPhonePresenter;
import com.azkj.album.utils.Utils;
import com.azkj.album.view.base.BaseActivity;
import com.azkj.album.view.iview.IBindView;
import com.azkj.album.view.widgets.TitleNavBar;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;


public class BindPhoneActivity extends BaseActivity implements IBindView {

    @BindView(R.id.titleBar)
    TitleNavBar mTitleBar;

    @BindView(R.id.register_phone)
    EditText mEtPhone;
    @BindView(R.id.register_code)
    EditText mEtCode;

    @BindView(R.id.tv_send_code)
    TextView mTvSend;

    @BindView(R.id.et_login_psd)
    EditText mEtPsd;
    @BindView(R.id.et_login_psd_again)
    EditText mEtPsd2;

    @BindView(R.id.tv_login_psd_visibility)
    ImageView mIvSee;
    @BindView(R.id.tv_login_psd_visibility_again)
    ImageView mIvSee2;

    @BindView(R.id.ll_username)
    LinearLayout mLayoutUser;

    @BindView(R.id.ll_psd)
    LinearLayout mLayoutPsd;

    @BindView(R.id.register_username)
    EditText mEtName;
    @BindView(R.id.register_user)
    TextView mTvNext;


    private BindPhonePresenter mPresenter;


    //0:绑定；1：忘记密码，2：修改密码
    private int mType;
    private String unionid;
    private String wx_username;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_bind_phone;
    }

    @Override
    public void initView() {
        mTitleBar.setLeftListener(v -> finish());
        mType = getIntent().getIntExtra("type", 0);
        unionid = getIntent().getStringExtra("unionid");
        wx_username = getIntent().getStringExtra("wx_username");
        mTitleBar.setTitle(mType == 0 ? "" : mType == 1 ? "忘记密码" : "修改密码");
        mTvNext.setText(mType == 0 ? "绑定手机号并登录" : mType == 1 ? "确定" : "确定");
        mLayoutPsd.setVisibility(mType == 0 ? View.GONE : View.VISIBLE);

        if (mType == 1) {
            mEtPhone.setHint("请输入注册时的手机号");
            mEtPsd.setHint("请输入新密码");
        } else if (mType == 2) {
            mEtPhone.setEnabled(false);
            mEtPhone.setText(ConfigStorage.getInstance().getUserBean().getUserinfo().getMobile());
            mEtPsd.setHint("请输入新密码");
        }

    }

    @Override
    public void initData() {

    }

    @OnClick({R.id.tv_login_psd_visibility, R.id.tv_login_psd_visibility_again, R.id.tv_send_code, R.id.register_user
    })
    public void onClick(View v) {
        if (Utils.isFastClick()) return;
        switch (v.getId()) {
            case R.id.tv_login_psd_visibility:
                if (mEtPsd.getTransformationMethod() == HideReturnsTransformationMethod
                        .getInstance()) {
                    mEtPsd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mIvSee.setImageResource(R.mipmap.icon_login_eye);
                } else {
                    mEtPsd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());  //密码以明文显示}
                    mIvSee.setImageResource(R.mipmap.icon_login_eye_open);
                }
                if (!TextUtils.isEmpty(mEtPsd.getText()))
                    mEtPsd.setSelection(mEtPsd.getText().length());
                break;
            case R.id.tv_login_psd_visibility_again:
                if (mEtPsd2.getTransformationMethod() == HideReturnsTransformationMethod
                        .getInstance()) {
                    mEtPsd2.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mIvSee2.setImageResource(R.mipmap.icon_login_eye);
                } else {
                    mEtPsd2.setTransformationMethod(HideReturnsTransformationMethod.getInstance());  //密码以明文显示}
                    mIvSee2.setImageResource(R.mipmap.icon_login_eye_open);
                }
                if (!TextUtils.isEmpty(mEtPsd2.getText()))
                    mEtPsd2.setSelection(mEtPsd2.getText().length());
                break;

            case R.id.tv_send_code:
                sendSMS();
                break;
            case R.id.register_user:
                nextStep();
                break;
        }

    }

    private void nextStep() {


        if (TextUtils.isEmpty(mEtPhone.getText().toString().trim())) {
            ToastUtils.showCenterToast("请输入手机号");
            return;
        }
        if (TextUtils.isEmpty(mEtCode.getText().toString().trim())) {
            ToastUtils.showCenterToast("请输入验证码");
            return;
        }
        Map<String, Object> map = HttpsUtil.getCommonPostRequest();

        if (mType == 0) {
            map.put("mobile", mEtPhone.getText().toString().trim());
            map.put("username", wx_username);
            map.put("code", mEtCode.getText().toString().trim());
            map.put("wx_unionid", unionid);
            mPresenter.bindPhone(map);
            return;
        }


        if (TextUtils.isEmpty(mEtPsd.getText().toString().trim())) {
            ToastUtils.showCenterToast("请输入密码");
            return;
        }
        if (TextUtils.isEmpty(mEtPsd2.getText().toString().trim())) {
            ToastUtils.showCenterToast("请再次输入密码");
            return;
        }

        if (!mEtPsd.getText().toString().trim().equals(mEtPsd2.getText().toString().trim())) {
            ToastUtils.showCenterToast("两次密码不一致");
            return;
        }

        map.put("mobile", mEtPhone.getText().toString().trim());
        map.put("newpassword", mEtPsd.getText().toString().trim());
        map.put("captcha", mEtCode.getText().toString().trim());
        mPresenter.changePsd(map);
    }

    private void sendSMS() {

        if (TextUtils.isEmpty(mEtPhone.getText().toString().trim())) {
            ToastUtils.showCenterToast("请输入手机号");
            return;
        }

        Map<String, Object> map = HttpsUtil.getCommonPostRequest();
        map.put("mobile", mEtPhone.getText().toString().trim());
        String event = "";
        if (mType == 0) {
            event = "thirdregister";
        } else {
            event = "resetpwd";
        }
        map.put("event", event);

        mPresenter.sendSMS(map);
    }

    //开启倒计时
    private void startTimer() {
        final Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            private int counter = 60;

            public void run() {

                runOnUiThread(() -> {
                    if (counter > 0) {
                        mTvSend.setText(String.format("%ds后重新发送", counter));
                    } else {
                        mTvSend.setText("发送验证码");
                        mTvSend.setEnabled(!TextUtils.isEmpty(mEtPhone.getText()));
                        mTvSend.setTextColor(getResources().getColor(R.color.color_blue));
                        timer.cancel();
                    }

                    counter--;
                });
            }
        };
        timer.schedule(task, 0L, 1000L);
        mTvSend.setEnabled(false);
        mTvSend.setTextColor(getResources().getColor(R.color.color_99));


    }

    @Override
    protected void initPresenter() {
        mPresenter = new BindPhonePresenter(this);
    }


    @Override
    public void sendSmsSuccess(TextView tv) {
        ToastUtils.showCenterToast("验证码已发送，请注意查收");
        startTimer();
    }

    @Override
    public void sendSmsFail(String msg) {
        ToastUtils.showCenterToast(msg);
    }

    @Override
    public void bindSuccess(LoginBean loginBean) {
        ToastUtils.showCenterToast("绑定成功");
        ConfigStorage.getInstance().saveUserBean(loginBean);
        EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_LOGIN_SUCCESS));
        Intent intent = new Intent(this, HomeActivity.class);
        startActivity(intent);
        finish();

    }

    @Override
    public void bindFail(String msg) {
        ToastUtils.showCenterToast(msg);
    }

    @Override
    public void changePsdSuccess() {

        if (mType == 1) {
            ToastUtils.showCenterToast("密码已重置");
            finish();
        } else {

            ToastUtils.showCenterToast("修改成功，请重新登录");
            StoreUtils.clear();
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }

    }

    @Override
    public void changePsdFail(String msg) {
        ToastUtils.showCenterToast(msg);
    }


    @Override
    public void checkSmsSuccess() {

    }

    @Override
    public void checkSmsFail(String msg) {

    }
}
